from telnet_tool import TelnetObj
import json
import re
import os


class Router:
    _telnet = None # telnet对象
    _expire_time = None # 过期时间
    # 初始化一个路由器
    def __init__(self,ip,passwd):
        # 新建一个telnet
        self._telnet = TelnetObj(ip,passwd)
        # pass

    # 从文件中读取出json
    def read_json_from_file(self, filename):
        with open(filename, 'r') as fp:
            return json.load(fp);
            
    # 初始化拓扑
    def init_topology(self, pathname):
        filename = 'config' + os.sep + pathname + os.sep + 'topo.json';
        print(filename)
        # 读取json格式的拓扑配置文件
        topo_config = self.read_json_from_file(filename)
        commands = [];
        # 查询命令
        qcs = []
        # 遍历每一个接口
        for k in topo_config:
            # 进入接口
            commands.append('int %s' % k)
            commands.append('ip address %s %s' % (topo_config[k]['ip'], topo_config[k]['mask']))
            commands.append('no shutdown')
            commands.append('exit')
            qcs.append('show ip interface %s' % k);
        # 应用拓扑
        # 执行多条命令
        self._telnet.execute_conf_commands(commands)
        print(commands)
        # 返回接口
        res = ''
        for qc in qcs:
            res += self._telnet.execute_query_command(qc);

        return res;

    # 配置acl
    def config_acl(self, pathname):
        filename = 'config' + os.sep + pathname + os.sep + 'acl.json';
        # 读取json格式的acl配置文件
        acl_config = self.read_json_from_file(filename)
        commands = [];
        # 查询命令
        qcs = []
        # 遍历每一个acl
        for k in acl_config['acl']:
            # 操作新建一个acl
            commands.append('ip access-list %s %s' % (acl_config['acl'][k]['type'],k));
            # 依次操作规则
            for rule in acl_config['acl'][k]['rules']:
                commands.append(rule);
            commands.append('exit')
        # 查询当前acl
        qcs.append("show ip access-list")
        # 遍历每一个接口
        for interface in acl_config['int']:
            # 如果这个接口不需要配置
            if acl_config['int'][interface]['in'] == '' and acl_config['int'][interface]['out'] == '':
                # 跳过不配置
                continue;
            commands.append("interface %s" % interface)
            # 如果需要在in口应用规则
            if acl_config['int'][interface]['in'] != '':
                commands.append('ip access-group %s in' % acl_config['int'][interface]['in']);
            # 如果需要在out口应用规则
            if acl_config['int'][interface]['out'] != '':
                commands.append('ip access-group %s out' % acl_config['int'][interface]['out']);
            commands.append("exit")
            # 查询接口acl
            qcs.append('show ip interface %s' % interface);
        # 应用acl
        # 执行多条命令
        self._telnet.execute_conf_commands(commands)

        # 返回接口
        res = ''
        for qc in qcs:
            res += self._telnet.execute_query_command(qc);

        return res;


    # 取消配置acl
    def no_config_acl(self, pathname):
        filename = 'config' + os.sep + pathname + os.sep + 'acl.json';
        # 读取json格式的acl配置文件
        acl_config = self.read_json_from_file(filename)
        commands = [];
        # 查询命令
        qcs = []
        # # 遍历每一个acl
        # for k in acl_config['acl']:
        #     # 操作新建一个acl
        #     commands.append('ip access-list %s %s' % (acl_config['acl'][k]['type'],k));
        #     # 依次操作规则
        #     for rule in acl_config['acl'][k]['rules']:
        #         commands.append(rule);
        #     commands.append('exit')
        # # 查询当前acl
        # qcs.append("show ip access-list")
        # 遍历每一个接口
        for interface in acl_config['int']:
            # 如果这个接口不需要配置
            if acl_config['int'][interface]['in'] == '' and acl_config['int'][interface]['out'] == '':
                # 跳过不配置
                continue;
            commands.append("interface %s" % interface)
            # 如果需要在in口应用规则
            if acl_config['int'][interface]['in'] != '':
                commands.append('no ip access-group %s in' % acl_config['int'][interface]['in']);
            # 如果需要在out口应用规则
            if acl_config['int'][interface]['out'] != '':
                commands.append('no ip access-group %s out' % acl_config['int'][interface]['out']);
            commands.append("exit")
            # 查询接口acl
            qcs.append('show ip interface %s' % interface);
        # 应用acl
        # 执行多条命令
        self._telnet.execute_conf_commands(commands)

        # 返回接口
        res = ''
        for qc in qcs:
            res += self._telnet.execute_query_command(qc);

        return res;

    # 检验acl
    def check_acl(self, pathname):
        # 读取json格式的acl检验文件
        filename = 'config' + os.sep + pathname + os.sep + 'check.json';
        # 读取json格式的acl配置文件
        check_config = self.read_json_from_file(filename)
        qcs = [];
        # 读取每一个ping语句
        for ping in check_config:
            # 加入到查询语句中
            qcs.append(ping);

        # 返回接口
        res = ''
        for qc in qcs:
            res += self._telnet.execute_query_command_slowly(qc);

        return res;

if __name__ == '__main__':
    r = Router('172.16.0.2','CISCO')
    # print(r.init_topology('R1'))
    print(r.config_acl('R1'))
    print(r.check_acl('R1'))
    # print(r.add_acl_for_int('FastEthernet0/0','test1',False))
    # print(r.get_int_map())
    # print(r.del_acl('standard!test'))
